import time,sys,random
import subprocess

def connect(mobile_ip,port):
    return subprocess.run("adb connect %s:%s"%(mobile_ip,port),shell=True)

def shell_cmd(cmd,delay):
    res = subprocess.run(cmd,shell=True)
    print(res)
    print('delay: %d\n'%delay)

    time.sleep(delay)
    ret=int(str(res).replace(")","").split("=")[-1])
    if ret != 0:
        connect()
        time.sleep(5)
    return ret

def control_app(mobile_ip,port):
    state=connect(mobile_ip,port)
    print("状态: ",state)
    #向上滑动
    cmd="adb -s %s:%s shell input swipe 310 650 310 200"%(mobile_ip,port)
    #点击屏幕
    cmd_point="adb -s %s:%s shell input tap 310 310"%(mobile_ip,port)
    #按返回键
    cmd_return="adb -s %s:%s shell input keyevent  4"%(mobile_ip,port)
    print('')
    
    i = 1
    return_interval = random.randint(4,8)    #按返回键间隔
    while i <= 1000:
        print("第%d个视频."%(i))
        delay = random.sample(range(5,15),10)
        ret = shell_cmd(cmd,delay[0])
        i += 1
        return_interval -= 1
        if return_interval <= 0:
            print("第%d个视频."%(i))
            shell_cmd(cmd_return,delay[1])
            i += 1
            return_interval = random.randint(4,8)          

if __name__=="__main__":
    mi4_ip = '192.168.150.98'  #mi4
    v9_ip  = '192.168.150.195' #V9

    port = "5555"
    #print(sys.argv)
    if len(sys.argv) > 1:
        mobile_model = sys.argv[1].lower()
        if  mobile_model == 'v9':
            mobile_ip = v9_ip
        else: 
            mobile_ip = mi4_ip
    else:   
        mobile_ip = mi4_ip
    
    control_app(mobile_ip,port)